# 从movie_user_api里面抄的，再改的
# token在这里
# 用户注册和用户登录的地方

import uuid

from flask_restful import Resource, reqparse, abort, fields, marshal

from App.apis.admin.model_utils import get_admin_user
from App.apis.api_constant import HTTP_CREATE_OK, USER_ACTION_LOGIN, USER_ACTION_REGISTER, HTTP_OK
from App.ext import cache
from App.models.admin import AdminUser


# parse用途：过滤数据
from App.settings import ADMINS
from App.token_utils import generate_admin_user_token

parse_base = reqparse.RequestParser()           # 这个是基础限制
parse_base.add_argument('password', type = str, required=True, help ='请输入密码')
parse_base.add_argument("action", type = str, required=True, help ="请确认请求参数（登录还是注册）")
parse_base.add_argument('username', type = str, required=True, help ='请输入用户名')

# fields用途：格式化数据
admin_user_fields = {
    "username":fields.String,
    "password":fields.String(attribute = "_password")
}

single_admin_user_fields = {
    "status": fields.Integer,
    "msg":fields.String,
    "data":fields.Nested(admin_user_fields)
}


class AdminUsersResource(Resource):

    # marshl_with
    def post(self):
        args = parse_base.parse_args()
        password = args.get('password')
        action = args.get("action").lower()
        username = args.get('username')
        if action == USER_ACTION_REGISTER:          # 注册分支
            admin_user = AdminUser(username = username , password = password)
            # 判断是否注册为超管
            if admin_user.username in ADMINS:
                admin_user.is_super = True

            if not admin_user.save():
                abort(400 , msg = '注册用户失败')
            data = {
                "status": HTTP_CREATE_OK,
                "msg": "注册用户成功",
                "data":admin_user       #一个对象本来不可序列化，但是用了marshal就可以了
            }
            return marshal(data, single_admin_user_fields)

        elif action == USER_ACTION_LOGIN:           # 登录分支
            user = get_admin_user(username)      # 在数据库里找，找得到就返回，找不到就返回none
            if not user:
                abort(400 , msg = "用户不存在")

            if not user.check_password(password):       # 检验密码是否错误
                abort(401 , msg = "密码错误")

            if user.is_delete:
                abort(401 , msg = "用户不存在")

            token = generate_admin_user_token()          # 走到这一步就证明用户密码都对得上了，就生成一个token，为后续操作准备
            cache.set(token , user.id , timeout = 60*60*24*7)       # 根据用户名去给它绑定一个token，放到缓存里面.token相当于键，id相当于值

            data = {
                "msg" : "login success",
                "status":HTTP_OK,
                "token": token
            }
            return data

        else:
            abort(400 , msg = "请提供正确的参数（登录还是注册）")



